package com.ruoyi.pos.service.impl.transaction;

import com.ruoyi.pos.domain.transaction.PosSale;
import com.ruoyi.pos.domain.transaction.PosSaleDetail;
import com.ruoyi.pos.domain.transaction.PosSalePay;
import com.ruoyi.pos.domain.dto.transaction.request.SaleTicketCreateRequest;
import com.ruoyi.pos.domain.dto.transaction.request.SaleTicketQueryRequest;
import com.ruoyi.pos.domain.dto.transaction.response.SaleTicketResponse;
import com.ruoyi.pos.domain.dto.common.response.BasePageResponse;
import com.ruoyi.pos.mapper.transaction.PosSaleMapper;
import com.ruoyi.pos.mapper.transaction.PosSaleDetailMapper;
import com.ruoyi.pos.mapper.transaction.PosSalePayMapper;
import com.ruoyi.pos.service.transaction.IPosSaleTicketService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * POS销售小票Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-30
 */
@Service
@Transactional(transactionManager = "posTransactionManager")
public class PosSaleTicketServiceImpl implements IPosSaleTicketService {

    @Autowired
    private PosSaleMapper posSaleMapper;

    @Autowired
    private PosSaleDetailMapper posSaleDetailMapper;

    @Autowired
    private PosSalePayMapper posSalePayMapper;

    /**
     * 创建销售小票
     * 
     * @param request 创建请求
     * @return 销售小票响应
     */
    @Override
    public SaleTicketResponse createSaleTicket(SaleTicketCreateRequest request) {
        SaleTicketResponse response = new SaleTicketResponse();
        
        try {
            // 创建销售主表
            PosSale sale = new PosSale();
            BeanUtils.copyBeanProp(sale, request);
            sale.setCreateTime(new Date());
            sale.setUpdateTime(new Date());
            sale.setTransactionStatus("1"); // 销售成功状态
            
            // 生成交易流水号
            if (StringUtils.isEmpty(sale.getTransactionNo())) {
                sale.setTransactionNo(generateTransactionNo());
            }
            
            int saleResult = posSaleMapper.insertPosSale(sale);
            if (saleResult <= 0) {
                response.setSuccess(false);
                response.setMessage("创建销售小票失败");
                return response;
            }
            
            // 创建销售明细
            if (request.getSaleDetails() != null && !request.getSaleDetails().isEmpty()) {
                for (SaleTicketCreateRequest.SaleDetailRequest detailRequest : request.getSaleDetails()) {
                    PosSaleDetail detail = new PosSaleDetail();
                    BeanUtils.copyBeanProp(detail, detailRequest);
                    detail.setTransactionId(sale.getTransactionId());
                    detail.setCreateTime(new Date());
                    
                    posSaleDetailMapper.insertPosSaleDetail(detail);
                }
            }
            
            // 创建支付信息
            if (request.getSalePays() != null && !request.getSalePays().isEmpty()) {
                for (SaleTicketCreateRequest.SalePayRequest payRequest : request.getSalePays()) {
                    PosSalePay pay = new PosSalePay();
                    BeanUtils.copyBeanProp(pay, payRequest);
                    pay.setTransactionId(sale.getTransactionId());
                    pay.setCreateTime(new Date());
                    
                    posSalePayMapper.insertPosSalePay(pay);
                }
            }
            
            // 构建响应
            response.setSuccess(true);
            response.setMessage("创建销售小票成功");
            BeanUtils.copyBeanProp(response, sale);
            
        } catch (Exception e) {
            response.setSuccess(false);
            response.setMessage("创建销售小票失败: " + e.getMessage());
        }
        
        return response;
    }

    /**
     * 验证销售小票数据完整性
     * 
     * @param request 验证请求
     * @return 验证结果
     */
    @Override
    public boolean validateSaleTicketData(SaleTicketCreateRequest request) {
        try {
            // 基本验证
            if (StringUtils.isEmpty(request.getTransactionNo())) {
                return false;
            }
            
            if (request.getTotalAmount() == null || request.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0) {
                return false;
            }
            
            if (request.getSaleDetails() == null || request.getSaleDetails().isEmpty()) {
                return false;
            }
            
            // 验证明细
            BigDecimal detailTotal = BigDecimal.ZERO;
            for (SaleTicketCreateRequest.SaleDetailRequest detail : request.getSaleDetails()) {
                if (detail.getQuantity() == null || detail.getQuantity() <= 0) {
                    return false;
                }
                if (detail.getUnitPrice() == null || detail.getUnitPrice().compareTo(BigDecimal.ZERO) <= 0) {
                    return false;
                }
                detailTotal = detailTotal.add(detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity())));
            }
            
            // 验证总金额
            if (request.getTotalAmount().compareTo(detailTotal) != 0) {
                return false;
            }
            
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 根据ID查询销售小票
     * 
     * @param saleId 销售ID
     * @return 销售小票信息
     */
    @Override
    public SaleTicketResponse getSaleTicketById(Long saleId) {
        try {
            PosSale sale = posSaleMapper.selectPosSaleById(saleId);
            if (sale == null) {
                return null;
            }
            
            SaleTicketResponse response = new SaleTicketResponse();
            BeanUtils.copyBeanProp(response, sale);
            response.setSuccess(true);
            
            return response;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 分页查询销售小票列表
     * 
     * @param request 查询请求
     * @return 分页响应
     */
    @Override
    public BasePageResponse<SaleTicketResponse> querySaleTickets(SaleTicketQueryRequest request) {
        PosSale sale = new PosSale();
        BeanUtils.copyBeanProp(sale, request);
        
        List<PosSale> sales = posSaleMapper.selectPosSaleList(sale);
        List<SaleTicketResponse> responses = sales.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        
        return new BasePageResponse<>(responses, sales.size());
    }

    /**
     * 验证退货权限
     * 
     * @param transactionId 原销售ID
     * @param cashierId 收银员ID
     * @return 是否有退货权限
     */
    @Override
    public boolean validateRefundPermission(Long transactionId, Long cashierId) {
        try {
            // 检查原销售是否存在
            PosSale originalSale = posSaleMapper.selectPosSaleById(transactionId);
            if (originalSale == null) {
                return false;
            }
            
            // 检查是否已经退货
            if ("2".equals(originalSale.getTransactionType())) {
                return false;
            }
            
            // 这里可以添加更复杂的权限检查逻辑
            // 比如检查退货时间限制、收银员权限等
            
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取可退货的交易
     * 
     * @param transactionNo 交易流水号
     * @return 可退货交易信息
     */
    @Override
    public SaleTicketResponse getRefundableTransaction(String transactionNo) {
        try {
            PosSale sale = posSaleMapper.selectPosSaleByTransactionNo(transactionNo);
            if (sale == null || !"1".equals(sale.getTransactionType())) {
                return null;
            }
            
            return convertToResponse(sale);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 验证是否可退货
     * 
     * @param originalSaleId 原销售ID
     * @return 是否可退货
     */
    @Override
    public boolean validateRefundable(Long originalSaleId) {
        try {
            PosSale originalSale = posSaleMapper.selectPosSaleById(originalSaleId);
            if (originalSale == null) {
                return false;
            }
            
            // 检查交易类型
            if (!"1".equals(originalSale.getTransactionType())) {
                return false;
            }
            
            // 检查支付状态
            if (!"1".equals(originalSale.getPaymentStatus())) {
                return false;
            }
            
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取退货记录
     * 
     * @param originalTransactionId 原销售ID
     * @return 退货记录列表
     */
    @Override
    public List<SaleTicketResponse> getRefundRecords(Long originalTransactionId) {
        PosSale sale = new PosSale();
        sale.setOriginalTransactionId(originalTransactionId);
        sale.setTransactionType("2"); // 退货类型
        
        List<PosSale> sales = posSaleMapper.selectPosSaleList(sale);
        return sales.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    /**
     * 获取收银员退货记录
     * 
     * @param cashierId 收银员ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 退货记录列表
     */
    @Override
    public List<SaleTicketResponse> getCashierRefundRecords(Long cashierId, String startTime, String endTime) {
        PosSale sale = new PosSale();
        sale.setUserId(cashierId);
        sale.setTransactionType("2"); // 退货类型
        // 可以在 Mapper 中处理时间范围查询
        
        List<PosSale> sales = posSaleMapper.selectPosSaleList(sale);
        return sales.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    /**
     * 根据原交易获取退货记录
     * 
     * @param originalSaleId 原销售ID
     * @return 退货记录列表
     */
    @Override
    public List<SaleTicketResponse> getRefundsByOriginalTransaction(Long originalSaleId) {
        try {
            List<PosSale> sales = posSaleMapper.selectRefundsByOriginalSaleId(originalSaleId);
            return sales.stream()
                    .map(this::convertToResponse)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 转换实体为响应DTO
     * 
     * @param sale 销售实体
     * @return 销售响应DTO
     */
    private SaleTicketResponse convertToResponse(PosSale sale) {
        SaleTicketResponse response = new SaleTicketResponse();
        BeanUtils.copyBeanProp(response, sale);
        response.setSuccess(true);
        return response;
    }

    /**
     * 生成交易流水号
     * 
     * @return 交易流水号
     */
    private String generateTransactionNo() {
        return "TXN" + System.currentTimeMillis();
    }

    // ==================== 补充缺失的接口方法 ====================

    /**
     * 根据流水号查询销售小票
     * 
     * @param transactionNo 销售流水号
     * @return 销售小票响应
     */
    @Override
    public SaleTicketResponse getSaleTicketByNo(String transactionNo) {
        try {
            PosSale sale = posSaleMapper.selectPosSaleByTransactionNo(transactionNo);
            if (sale == null) {
                return null;
            }
            return convertToResponse(sale);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 更新销售小票状态
     * 
     * @param transactionId 销售ID
     * @param status 新状态
     * @return 是否成功
     */
    @Override
    public boolean updateSaleTicketStatus(Long transactionId, String status) {
        try {
            PosSale sale = new PosSale();
            sale.setTransactionId(transactionId);
            sale.setTransactionStatus(status);
            sale.setUpdateTime(new Date());
            
            return posSaleMapper.updatePosSale(sale) > 0;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 取消销售小票
     * 
     * @param transactionId 销售ID
     * @param reason 取消原因
     * @return 是否成功
     */
    @Override
    public boolean cancelSaleTicket(Long transactionId, String reason) {
        try {
            PosSale sale = new PosSale();
            sale.setTransactionId(transactionId);
            sale.setTransactionStatus("3"); // 3-撤销
            sale.setRemark(reason);
            sale.setUpdateTime(new Date());
            
            return posSaleMapper.updatePosSale(sale) > 0;
        } catch (Exception e) {
            return false;
        }
    }
}
